var express = require('express')
var router = express.Router()
const connection = require('../db/sql.js')
const User = require('../db/UserSql')
const Qcloudsms = require('qcloudsms_js')
const jwt = require('jsonwebtoken')
const alipaySdk = require('../db/alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default
const axios = require('axios')
/* GET home page. */
// 首页
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' })
})

// 首页推荐
router.get('/api/index_list/0/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: {
      topBar: [
        { id: 0, label: '推荐' },
        { id: 1, label: '手机' },
        { id: 2, label: '智能' },
        { id: 3, label: '家电' },
        { id: 4, label: '笔记本' }
      ],
      data: [
        {
          id: 0,
          type: 'swiperList',
          data: [
            {
              id: 0,
              imgUrl: './img/swiper01.jpg'
            },
            {
              id: 1,
              imgUrl: './img/swiper02.jpg'
            }
          ]
        },
        {
          id: 1,
          type: 'iconsList',
          data: [
            {
              id: 0,
              imgUrl: './img/miaosha.png'
            },
            {
              id: 1,
              imgUrl: './img/note.webp'
            },
            {
              id: 2,
              imgUrl: './img/miaosha.png'
            },
            {
              id: 3,
              imgUrl: './img/note.webp'
            },
            {
              id: 4,
              imgUrl: './img/miaosha.png'
            },
            {
              id: 5,
              imgUrl: './img/note.webp'
            },
            {
              id: 6,
              imgUrl: './img/miaosha.png'
            },
            {
              id: 7,
              imgUrl: './img/note.webp'
            },
            {
              id: 8,
              imgUrl: './img/miaosha.png'
            },
            {
              id: 9,
              imgUrl: './img/note.webp'
            }
          ]
        },
        {
          id: 2,
          type: 'adList',
          data: [
            {
              id: 1,
              imgUrl1: './img/mi11.webp',
              imgUrl2: './img/shi.webp',
              imgUrl3: './img/huan.webp'
            }
          ]
        },
        {
          id: 3,
          type: 'recommdList',
          data: [
            {
              id: 0,
              imgUrl: './img/11pro.jpg',
              name: '小米11 Pro',
              content: "1.12''GN2｜骁龙888",
              pprice: '3999'
            },
            {
              id: 1,
              imgUrl: './img/11pro.jpg',
              name: '小米12 Pro',
              content: "1.12''GN2｜骁龙888",
              pprice: '4999'
            }
          ]
        }
      ]
    }
  })
})

// 首页 手机
router.get('/api/index_list/1/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        id: 0,
        type: 'ads',
        data: [
          {
            id: 0,
            imgUrl: './img/ad.webp'
          }
        ]
      }
    ]
  })
})

// 首页智能
router.get('/api/index_list/2/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        id: 0,
        type: 'swiperList',
        data: [
          {
            id: 0,
            imgUrl: './img/swiper01.jpg'
          },
          {
            id: 1,
            imgUrl: './img/swiper02.jpg'
          }
        ]
      },
      {
        id: 1,
        type: 'iconsList',
        data: [
          {
            id: 0,
            imgUrl: './img/miaosha.png'
          },
          {
            id: 1,
            imgUrl: './img/note.webp'
          },
          {
            id: 2,
            imgUrl: './img/miaosha.png'
          },
          {
            id: 3,
            imgUrl: './img/note.webp'
          },
          {
            id: 4,
            imgUrl: './img/miaosha.png'
          },
          {
            id: 5,
            imgUrl: './img/note.webp'
          },
          {
            id: 6,
            imgUrl: './img/miaosha.png'
          },
          {
            id: 7,
            imgUrl: './img/note.webp'
          },
          {
            id: 8,
            imgUrl: './img/miaosha.png'
          },
          {
            id: 9,
            imgUrl: './img/note.webp'
          }
        ]
      }
    ]
  })
})

// 分类数据
router.get('/api/goods/list', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        id: 0,
        name: '小米手机',
        data: [
          {
            id: 0,
            title: '小米数字系列',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '小米11 Ultra'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: '小米11 Pro'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '小米11 青春版'
              },
              {
                id: 3,
                imgUrl: './img/list01.png',
                name: '小米10s'
              }
            ]
          },
          {
            id: 1,
            title: '小米MIX系列',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: 'MIX FOLD'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'MIN Alpha'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '小米11 青春版'
              },
              {
                id: 3,
                imgUrl: './img/list01.png',
                name: '小米10s'
              }
            ]
          },
          {
            id: 0,
            title: '小米手机配件',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '无线充'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: '充电器'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '数据线'
              },
              {
                id: 3,
                imgUrl: './img/list01.png',
                name: '充电宝'
              }
            ]
          }
        ]
      },
      {
        id: 1,
        name: 'Redmi手机',
        data: [
          {
            id: 0,
            title: 'Redimi红米 Note系列',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: 'Note 9 Pro'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'Note 9'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Note 9 4G'
              },
              {
                id: 3,
                imgUrl: './img/list01.png',
                name: 'Note 8 Pro'
              },
              {
                id: 4,
                imgUrl: './img/list01.png',
                name: 'Redmi Note 8'
              }
            ]
          },
          {
            id: 1,
            title: 'Redimi红米 K系列',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: 'K40游戏增强版'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          },
          {
            id: 2,
            title: 'Redimi红米 X系列',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '10X 5G'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: '10X Pro 5G'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '10X 4G'
              }
            ]
          }
        ]
      },
      {
        id: 2,
        name: '游戏手机',
        data: [
          {
            id: 0,
            title: '游戏手机',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: 'K40游戏增强版'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: '黑鲨 4 Pro'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '黑鲨 4'
              }
            ]
          },
          {
            id: 1,
            title: '游戏手机配件',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '黑鲨游戏耳机'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: '冰封散热背夹'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: '黑鲨手游肩连'
              }
            ]
          }
        ]
      },
      {
        id: 3,
        name: '智能穿戴',
        data: [
          {
            id: 0,
            title: '智能穿戴',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '智能手表'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 4,
        name: '电视',
        data: [
          {
            id: 0,
            title: '电视',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '32-43英寸'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 5,
        name: '电脑办公',
        data: [
          {
            id: 0,
            title: '小米笔记本',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: 'Pro 15'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 6,
        name: '大家电',
        data: [
          {
            id: 0,
            title: '空调',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '1匹挂机'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 7,
        name: '小家电',
        data: [
          {
            id: 0,
            title: '地面清洁',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '扫地机器人'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 8,
        name: '智能家居',
        data: [
          {
            id: 0,
            title: '智能安防',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '智能门锁'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 9,
        name: '户外出行',
        data: [
          {
            id: 1,
            title: '户外出行',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '助力车'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 10,
        name: '日用百货',
        data: [
          {
            id: 0,
            title: '家居日用',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '暖宝宝'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      },
      {
        id: 11,
        name: '儿童用品',
        data: [
          {
            id: 0,
            title: '儿童用品',
            list: [
              {
                id: 0,
                imgUrl: './img/list01.png',
                name: '益智积木'
              },
              {
                id: 1,
                imgUrl: './img/list01.png',
                name: 'K40 Pro系列'
              },
              {
                id: 2,
                imgUrl: './img/list01.png',
                name: 'Redmi K40'
              }
            ]
          }
        ]
      }
    ]
  })
})

// 商品接口
router.get('/api/goods/shoplist', function (req, res, next) {
  const [searchName, orderName] = Object.keys(req.query)
  const [name, order] = Object.values(req.query)
  console.log(searchName, orderName, name, order)
  if (orderName === 'undefined') {
    connection.query('select * from shoplist where title like "%' + name + '%"', function (error, results) {
      if (error) throw error
      res.send({
        code: 0,
        data: results
      })
    })
  } else {
    connection.query('select * from shoplist where title like "%' + name + '%" order by ' + orderName + ' ' + order + '', function (error, results) {
      if (error) throw error
      res.send({
        code: 0,
        data: results
      })
    })
  }
})

// 商品详情接口
router.get('/api/goods/id', function (req, res, next) {
  const id = req.query.id
  connection.query('select * from shoplist where id = ' + id + '', function (error, result) {
    if (error) throw error
    res.json({
      code: 0,
      data: result
    })
  })
})

// 登录
router.post('/api/login', function (req, res, next) {
  const params = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  // 查询用户名或者手机是否存在
  connection.query(User.queryUserName(params), function (eroor, results) {
    if (results.length > 0) {
      // 查询密码
      connection.query(User.queryUserPwd(params), function (error, result) {
        if (error) return error
        if (result.length > 0) {
          res.send({
            code: 0,
            data: {
              success: true,
              msg: '登录成功',
              data: [
                {
                  id: result[0].id,
                  token: result[0].token,
                  nick: result[0].nick,
                  imgUrl: result[0].imgUrl
                }
              ]
            }
          })
          console.log(result[0].id)
        } else {
          res.send({
            code: 0,
            data: {
              success: false,
              msg: '密码不对'
            }
          })
        }
      })
    } else {
      // 不存在
      res.send({
        code: 0,
        data: {
          success: false,
          msg: '用户名或手机号不存在'
        }
      })
    }
  })
})

// 手机验证码登录
router.post('/api/loginCode', function (req, res, nexxt) {
  const tel = req.body.phone
  // 短信应用 sdk appid
  // 根据腾讯SDK 来设计
  var appid = 1400187558
  var appkey = 'dc9dc3391896235ddc2325685047edc7'
  var phoneNumbers = [tel]
  var templateId = 285590
  var smsSign = '三人行慕课'
  var qcloudsms = Qcloudsms(appid, appkey)
  function callback (err, ress, resData) {
    if (err) {
      console.log('err:', err)
    } else {
      res.send({
        code: 0,
        data: {
          success: true,
          data: ress.req.body.params[0]
        }
      })
    }
  }
  var ssender = qcloudsms.SmsSingleSender()
  var params = [Math.floor(Math.random() * (9999 - 1000)) + 1000]
  ssender.sendWithParam('86', phoneNumbers, templateId, params, smsSign, '', '', callback)
})

// 增加用户
router.post('/api/addUser', function (req, res, next) {
  // 后端拿到前端传递过来的数据==>手机号
  const params = {
    userName: req.body.phone
  }
  // 查询用户是否存在
  connection.query(User.queryUserName(params), function (error, results) {
    // 如果数据存在
    if (error) throw error
    if (results.length > 0) {
      res.send({
        code: 0,
        data: {
          success: true,
          msg: '登录成功',
          data: [
            {
              id: results[0].id,
              token: results[0].token,
              nick: results[0].nick,
              imgUrl: results[0].imgUrl
            }
          ]
        }
      })
    } else {
      // 如果没有新增一条数据
      // console.log(insert into user (name,phone,password,nick,imgUrl,token) values ("vv","' + option.userName + '","666666","' + option.userName + '","img/nick.png","434343sf")
      connection.query(User.insertData(params), function (err, result) {
        if (err) throw err
        // 查询结果给前端返回用户数据
        connection.query(User.queryUserName(params), function (e, r) {
          res.send({
            code: 0,
            data: {
              success: true,
              msg: '注册并且登录成功',
              data: [
                {
                  id: r[0].id,
                  token: r[0].token,
                  nick: r[0].nick,
                  imgUrl: r[0].imgUrl
                }
              ]
            }
          })
        })
      })
    }
  })
})

// 加入购物车
router.post('/api/addCart', function (req, res, next) {
  // 解析token
  const token = req.headers.token
  const phone = jwt.decode(token)
  // 获取前端传递数据
  const goodsId = req.body.goodsId
  const goodsNum = req.body.goodsNum
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const userId = results[0].id
    connection.query(`select * from shoplist where id = ${goodsId}`, function (err, result) {
      if (err) throw err
      const goodsName = result[0].name
      const goodsPrice = result[0].price
      const goodsImgUrl = result[0].imgUrl
      // 直接添加
      // 如果有就
      connection.query(`select * from goods_cart where uId =${userId} and goods_id=${goodsId}`, function (err, data) {
        if (err) throw err
        if (data.length > 0) {
          const newNum = parseInt(data[0].goods_num) + parseInt(goodsNum)
          connection.query(`update goods_cart set goods_num = replace(goods_num,${data[0].goods_num},${newNum}) where id = ${data[0].id}`, function (e, r) {
            if (e) throw e
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '添加成功'
              }
            })
          })
        } else {
          connection.query(`insert into goods_cart (goods_id,goods_name,goods_num,goods_price,goods_imgUrl,uId) values('${goodsId}','${goodsName}','${goodsNum}','${goodsPrice}','${goodsImgUrl}','${userId}')`, function (e, r) {
            if (e) throw e
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '加入购物车成功'
              }
            })
          })
        }
      })
    })
  })
})

// 查询购物车数据
router.post('/api/selectCart', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    connection.query(`select * from goods_cart where uId = ${uId}`, function (err, result) {
      if (err) throw err
      res.send({
        code: 0,
        data: {
          success: true,
          data: result
        }
      })
    })
  })
})

// 修改 购物车数据
router.post('/api/updataNumCart', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  // 修改
  const goodsId = req.body.goodsId
  const goodsNum = req.body.goodsNum
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    connection.query(`select * from goods_cart where uId = ${uId} and goods_id=${goodsId}`, function (err, result) {
      if (err) throw err
      // 获取数据库中原路的数据
      const num = result[0].goods_num
      // 修改当前数据中
      const id = result[0].id
      connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${goodsNum}) where id = ${id}`, function (e, r) {
        if (e) throw e
        res.send({
          code: 0,
          data: {
            success: true,
            msg: '修改成功'
          }
        })
      })
    })
  })
})

// 删除 购物车updataNumCart
router.post('/api/deleteCart', function (req, res, next) {
  const id = req.body.id
  connection.query(`delete from goods_cart where id = ${id}`, function (err, result) {
    if (err) throw err
    res.send({
      code: 0,
      data: {
        success: true,
        msg: '删除成功'
      }
    })
  })
})

// 地址查询
router.post('/api/selectAddress', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    connection.query(`select * from address where uId = ${uId}`, function (err, result) {
      if (err) throw err
      res.send({
        code: 0,
        data: {
          success: true,
          data: result
        }
      })
    })
  })
})

// 新增地址
router.post('/api/addAddress', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  const content = req.body.content
  const [name, tel, province, city, country, county, addressDetail, areaCode, postalCode, isDefault] = [
    content.name,
    content.tel,
    content.province,
    content.city,
    content.country,
    content.county,
    content.addressDetail,
    content.areaCode,
    content.postalCode,
    content.isDefault
  ]
  console.log(name, tel, province, city, country, county, addressDetail, areaCode, postalCode, isDefault)
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    if (isDefault) {
      connection.query(`update address set isDefault = replace(isDefault,'true','false') where uId = ${uId}`, function (err, result) {
        if (err) throw err
        connection.query(`insert into address (name, tel, province, city, country, county, addressDetail, areaCode, postalCode, isDefault,uId) values ('${name}', '${tel}', '${province}', '${city}', '${country}', '${county}', '${addressDetail}', '${areaCode}', '${postalCode}', '${isDefault}','${uId}')`, function (err, result) {
          if (err) throw err
          res.send({
            code: 0,
            data: {
              success: true,
              msg: '新增成功'
            }
          })
        })
      })
    } else {
      connection.query(`insert into address (name, tel, province, city, country, county, addressDetail, areaCode, postalCode, isDefault,uId) values ('${name}', '${tel}', '${province}', '${city}', '${country}', '${county}', '${addressDetail}', '${areaCode}', '${postalCode}', '${isDefault}','${uId}')`, function (err, result) {
        if (err) throw err
        res.send({
          code: 0,
          data: {
            success: true,
            msg: '新增成功'
          }
        })
      })
    }
  })
})
// 修改收获地址
router.post('/api/updateAddress', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  const content = req.body.content
  const aId = req.body.aId
  const [name, tel, province, city, country, county, addressDetail, areaCode, postalCode, isDefault] = [
    content.name,
    content.tel,
    content.province,
    content.city,
    content.country,
    content.county,
    content.addressDetail,
    content.areaCode,
    content.postalCode,
    content.isDefault
  ]
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    if (isDefault) {
      connection.query(`update address set isDefault = replace(isDefault,'true','false') where uId = ${uId}`, function (err, result) {
        if (err) throw err
        connection.query(`update address set name='${name}',tel='${tel}',province='${province}',city='${city}',country='${country}',county='${county}',addressDetail='${addressDetail}',areaCode='${areaCode}',postalCode='${postalCode}',isDefault='${isDefault}',uId='${uId}' where id = ${aId}`, function (err, result) {
          if (err) throw err
          res.send({
            code: 0,
            data: {
              success: true,
              msg: '更新成功'
            }
          })
        })
      })
    } else {
      connection.query(`update address set name='${name}',tel='${tel}',province='${province}',city='${city}',country='${country}',county='${county}',addressDetail='${addressDetail}',areaCode='${areaCode}',postalCode='${postalCode}',isDefault='${isDefault}',uId='${uId}' where id = ${aId}`, function (err, result) {
        if (err) throw err
        res.send({
          code: 0,
          data: {
            success: true,
            msg: '更新成功'
          }
        })
      })
    }
  })
})

// 删除收获地址
router.post('/api/deleteAddress', function (req, res, next) {
  // const token = req.headers.token
  // const phone = jwt.decode(token)
  const id = req.body.id
  connection.query(`delete from address where id = ${id}`, function (err, result) {
    if (err) throw err
    res.send({
      code: 0,
      data: {
        success: true,
        msg: '删除成功'
      }
    })
  })
})

// 发起支付
router.post('/api/payment', async function (req, res, next) {
  // const token = req.headers.token
  // const phone = jwt.decode(token)
  // 获取订单号
  const orderId = req.body.orderId
  // 支付宝格式
  const formData = new AlipayFormData()
  formData.setMethod('get')
  formData.addField('notifyUrl', 'http://www.com/notify')
  formData.addField('bizContent', {
    outTradeNo: orderId,
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: '1.99',
    subject: '商品',
    body: '商品详情'
  })
  // 发起支付 支付成功或失败都会跳转
  formData.addField('returnUrl', 'http://localhost:8080/pay-success')

  const result = await alipaySdk.exec(
    'alipay.trade.page.pay',
    {},
    { formData: formData }
  )
  res.send({
    code: 0,
    data: {
      success: true,
      msg: '支付中...',
      paymentUrl: result
    }
  })
})

// 支付状态
router.post('/api/queryOrderAlipay', function (req, res, next) {
  // 订单号
  const outTradeNo = req.body.out_trade_no
  const tradeNo = req.body.trade_no
  const formData = new AlipayFormData()
  formData.setMethod('get')
  formData.addField('bizContent', {
    outTradeNo,
    tradeNo
  })

  const result = alipaySdk.exec(
    'alipay.trade.query',
    {},
    { formData: formData }
  )
  result.then(resData => {
    axios({
      method: 'get',
      url: resData
    }).then(data => {
      const r = data.data.alipay_trade_query_response
      // 订单ok
      if (r.code === '10000') {
        switch (r.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '交易创建，等待买家付款'
              }
            })
            break
          case 'TRADE_CLOSED':
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '未付款或超时导致交易关闭'
              }
            })
            break
          case 'TRADE_FINISHED':
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '交易完成,不可退款'
              }
            })
            break
          case 'TRADE_SUCCESS':
            res.send({
              code: 0,
              data: {
                success: true,
                msg: '交易成功'
              }
            })
            break
        }
      } else if (r.code === '40004') {
        res.send({
          code: 0,
          data: {
            success: true,
            msg: '交易不存在'
          }
        })
      }
    }).catch(err => {
      res.send({
        code: 0,
        data: {
          err,
          msg: '查询失败'
        }
      })
    })
  })
})

// 生成一个订单
router.post('/api/addOrder', function (req, res, next) {
  const token = req.headers.token
  const phone = jwt.decode(token)
  // 接收前端传递过来的数组
  const goodsArr = req.body.arr
  // 订单号生成 时间戳 + 6位随机数
  function orderCode () {
    var orderCode = ''
    for (var i = 0; i < 6; i++) {
      orderCode += Math.floor(Math.random() * 10)
    }
    orderCode = new Date().getTime() + orderCode // 时间戳，用来生成订单号。
    console.log(orderCode)
    return orderCode
  }
  connection.query(`select * from user where phone = ${phone.name}`, function (error, results) {
    if (error) throw error
    const uId = results[0].id
    // 0表示失败
    // 1表示未支付
    // 2表示待支付
    // 3表示支付成功
    // 这里要循环
    goodsArr.forEach(v => {
      // 添加到订单表
      connection.query(`insert into orderShop (uId,orderId,goods_name,goods_price,goods_num,order_status) values('${uId}','${orderCode()}','${v.goods_name}','${v.goods_price}','${v.goods_num}','1')`, function (err, result) {
        if (err) throw err
      })
      // 购物车中数据的清除
      connection.query(`delete from goods_cart where goods_id = ${v.goods_id}`, function (e, r) {
        if (e) throw e
      })
    })
    res.send({
      code: 0,
      data: {
        success: true
      }
    })
  })
})
module.exports = router
